<template>
  <div class="content">
    <div class="user-box">
      <div class="user-head-box box-bg">
        <span class="logout">
          <el-tooltip
            class="item"
            effect="dark"
            content="退出登陆"
            placement="left"
          >
            <i
              v-show="isLogin"
              class="el-icon-minus publish-text"
              style="top: 64px"
              @click="logout"
            ></i>
          </el-tooltip>
        </span>
        <div class="fr" style="flex-wrap: wrap">
          <div class="avtar-box">
            <el-badge :value="null" class="item">
              <el-avatar
                v-if="isLogin"
                class="avtar"
                :src="`${serveIp}${user.avatar}`"
                @error="errorAvatarHandler"
                @click="handleAvatarClick"
                style="cursor: pointer"
              >
              </el-avatar>
            </el-badge>
            <div class="moblie-box">
              <el-row :gutter="24">
                <el-col align="center" :span="8" :offset="0">
                  <strong>关注</strong>
                  <br />
                  0
                </el-col>
                <el-col align="center" :span="8" :offset="0">
                  <strong>粉丝</strong>
                  <br />
                  0
                </el-col>
                <el-col align="center" :span="8" :offset="0">
                  <strong>文章</strong>
                  <br />
                  0
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="user-info">
            <div class="fr top" style="flex-wrap: wrap">
              <h3 style="width: 100%; flex: 1">{{ user.nickname }}</h3>
              <div class="computer-box">
                <el-row :gutter="24">
                  <el-col align="center" :span="8" :offset="0">
                    <strong>关注</strong>
                    <br />
                    69
                  </el-col>
                  <el-col align="center" :span="8" :offset="0">
                    <strong>粉丝</strong>
                    <br />
                    2.4k
                  </el-col>
                  <el-col align="center" :span="8" :offset="0">
                    <strong>文章</strong>
                    <br />
                    {{ userPressCount||0 }}
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="desc">
              {{ user.description }}
            </div>
          </div>
        </div>
      </div>

      <!-- 文章列表 -->
      <div class="user-press-box box-bg">
      <div class="title"><span>我的文章</span> <a style="font-size:14px;" @click="goPublishPress">发布</a></div>
        <div>
          <div class="message-box">
            <div class="message-contnet-list"  >
              <div class="press-row" v-for="(item, i) in list" :key="i" @click="goDetail(item.id)">
                <div class="press-body-box">
                  <div class="press-title text-ellipsis" @click="goDetail(item.id)">
                    {{ item.title }}
                  </div>
                </div>
                <div v-if="item.cover" >
                  <a  @click="goDetail(item.id)" ><img class="press-cover" :src="`${serveIp}${item.cover}`" alt=""></a>
                </div>
                <div class="press-right-tag" v-if="item.tags.length != 0">
                  <span class="tag" v-for="(tag, index) in item.tags" :key="index">
                    {{ tag }}
                  </span>
                </div>
                <div class="press-time">{{ formatDate(item.publishDate) }} <span  style="margin-left:18px;"> By  <a href="#">{{item.user.nickname}}</a></span></div>
              </div>
            </div>
            <el-empty v-if="list.length === 0" :image-size="200"></el-empty>
            <el-pagination
              v-show="list.length !== 0"
              class="pager"
              small
              background
              layout="prev, pager, next"
              :total="total"
              :page-size="query.pageSize"
              :current-page="query.pageNum"
              @current-change="changePage"
              :page-count="5"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>


    <div class="plus-box">
      <vue-quick-calendar
        class="components-box box-bg d-none d-xl-block"
        showPrepNext
        :startYearMonth="checkedDate"
        :markDate="markDate"
        :checkedDate="checkedDate"
        @clickDate="clickDate"
        @changeMonth="changeMonth"
      />
      <!-- <div class="components-box box-bg d-none d-xl-block">小组件</div>
      <div class="components-box box-bg d-none d-xl-block">小组件</div>
      <div class="components-box box-bg d-none d-xl-block">小组件</div> -->
    </div>
  </div>
</template>

<script>
import vueQuickCalendar from "vue-quick-calendar";
import DateFormat, { masks } from "dateformat";
import CommonApi from "../api/common";
import UserApi from "../api/user";
import PressApi from "../api/press";
export default {
  data() {
    return {
      serveIp:'',
      markDate: [],
      date: "",
      checkedDate: "",
      isLogin: false,
      user: {},
      query:{
        pageNum:1,
        pageSize:8,
        topicId: null,
        userId:null
      },
      total:null,
      list: [],
      userPressCount:0,
    };
  },
  components: {
    vueQuickCalendar,
  },
  methods: {
    // 点击日期
    clickDate(date) {
      console.log(date);
    },
    // 切换月份
    changeMonth(date) {
      console.log(date);
    },
    errorAvatarHandler() {
      return true;
    },
    logout() {
      this.$confirm("是否要退出登陆？")
        .then((r) => {
          window.localStorage.removeItem("token");
          window.localStorage.removeItem("userInfo");
          this.user = {};
          this.isLogin = false;
          this.$message.success("已退出登陆");
          setTimeout(() => {
            this.$router.push("/welcome");
          }, 700);
        })
        .catch((e) => {});
    },
    //跳转发布文章
    goPublishPress() {
      this.$router.push("/publishPress");
    },
    getUser() {
      //先检查本地存储是否存在用户数据
      let tempUser = window.localStorage.getItem("userInfo");
      if (tempUser) {
        //如果本地存储有数据直接用
        this.isLogin = true;
        this.user = JSON.parse(tempUser);
        console.log(this.user);
        //获取用户信息后再查询关于用户的文章列表
        this.query.userId = this.user.id
        this.getList();
        PressApi.getUserPressCount(this.query.userId).then(res => {
          if (res.code === 200) {
            this.userPressCount = res.data; // 假设后端返回数量在data字段
          }
        });
      }
      //判断是否登陆状态
      if (!window.localStorage.getItem("token")) {
        return;
      }
      UserApi.getUser()
        .then((r) => {
          if (r.code == 200) {
            this.isLogin = true;
            this.user = r.data;
            //将用户数据存储在本地存储中
            window.localStorage.setItem("userInfo", JSON.stringify(r.data));
          } else {
            this.isLogin = false;
          }
        })
        .catch((e) => {});
    },
    changePage(val){
      this.query.pageNum = val
      this.getList()
    },
    /**
     * 获取列表数据
     */
    getList() {
      console.log(this.query);
      PressApi.getList(this.query).then((r) => {
        this.list = [];
        document.documentElement.scrollTop = 0;
        this.total = r.total
        if (r.code === 200) this.list = r.data;
      });
    },
    goDetail(val) {
      if (val){
        //////本页面打开
        this.$router.push({
          path: "/pressDetail/" + val,
        });
        // //////新页面打开
        // let routeUrl = this.$router.resolve({ 
        //   path: "/pressDetail/" + val,
        // });
        // window.open(routeUrl.href, '_blank');
      }
    },
    formatDate(val) {
      return DateFormat(val, "yyyy年 mm月 dd日 HH:MM:ss");
    },
    handleAvatarClick() {

      // 创建文件输入框
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      
      input.onchange = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        // 检查文件大小（限制为2MB）
        if (file.size > 2 * 1024 * 1024) {
          this.$message.error('图片大小不能超过2MB');
          return;
        }
        
        // 检查文件类型
        if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
          this.$message.error('只能上传jpg/png/gif格式的图片');
          return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);

        // 上传头像
        CommonApi.upload(formData).then(r => {
          if (r.code === 200) {
            // 更新用户头像
            UserApi.updateUser({
              ...this.user,
              avatar: r.data.imgUrl
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('头像更新成功');
                // 更新本地存储和页面显示
                this.user.avatar = r.data.imgUrl;
                window.localStorage.setItem('userInfo', JSON.stringify(this.user));
              } else {
                this.$message.error('头像更新失败');
              }
            }).catch(err => {
              this.$message.error('头像更新失败');
            });
          } else {
            this.$message.error('图片上传失败');
          }
        }).catch(err => {
          this.$message.error('图片上传失败');
        });
      };

      // 触发文件选择
      input.click();
    },
  },
  async mounted() {
    const token = window.localStorage.getItem("token");
    if (!token) {
      this.$message.error("请先登陆");
      this.$router.push("/login");
    }
    await CommonApi.getIp().then((r) => {
      this.serveIp = `${r.data}`;
      this.getUser();
    });
  },
  created() {
    this.checkedDate = DateFormat(new Date(), "yyyy-mm-dd");

  },
};
</script>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.user-box {
  width: 1000px;
  max-width: 1000px;
  .user-head-box {
    min-height: 200px;
    padding: 24px;
    .logout {
      position: absolute;
      right: 24px;
      top: 12px;
    }
    .avtar-box {
      margin-right: 24px;
      .avtar {
        border: 2px solid #f7f7f7;
        border-radius: 50%;
        overflow: hidden;
        min-width: 124px;
        min-height: 124px;
        flex: 1;
        transition: all 0.3s;
        &:hover {
          transform: scale(1.05);
          box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
      }
    }
    .user-info {
      margin-top: 24px;
      flex: 1;
      transition: all 0.3s;

      .desc {
        margin-top: 20px;
        transition: all 0.3s;
      }
      // flex: 1;
    }
    .moblie-box {
      display: none;
      font-size: 12px;
      flex: 1;
    }
    .computer-box {
      flex: 1;
      max-width: 200px;
      margin-left: 32px;
      .el-row {
        // margin-top: 24px;
      }
    }
  }
  .user-press-box {
    min-height: 800px;
    padding: 24px;
  }
}
.components-box {
  width: 400px;
  max-width: 360px;
  min-height: 200px;
  &.changeMonth {
    border-bottom: none !important;
  }
}

.box-bg {
  background-color: var(--bg-color);
  backdrop-filter: var(--bg-filter-blur);
  box-shadow: var(--box-shadow);
  border-radius: var(--box-radius);
  border: none;
}

/////////////////文章样式
.title {
  font-size: 24px;
  position: relative;
  left: 8px;
  display: flex;
  justify-content: space-between;
  justify-items: center;
  align-items: center;
  align-content: center;
}
.message-box {
  width: 100%;
}

.press-row {
  // background-color: #40A070;
  padding: 0px 24px 18px 24px;
  margin-top: 18px;
  border-bottom: 1px solid #c5c5c5;
  // border-radius: var(--box-radius);
  transition: 0.3s;

  .press-time {
    margin-top: 4px;
    font-size: 12px;
    color: #777777;
  }
  .press-body-box {
    display: flex;
    flex-direction: row;
    flex: 1;
    flex-wrap: wrap;
    .press-title {
      -webkit-line-clamp: 3;
      margin-top: 12px;
      color: #474747;
      font-size: 18px;
      font-weight: 600;
      margin-right: 24px;
      transition: 0.3s;
      &:hover {
        color: var(--font-color-hover);
        cursor: pointer;
      }
    }
  }
  .press-right-tag {
    width: 100%;
    padding: 6px 0px 0px 0px;
    flex-wrap: wrap;
    max-width: 200px;
    background-color: red($color: #000000);
    .tag {
      display: inline-flex;
      font-size: 10px;
      margin: 0px 4px 0px 0px;
      padding: 2px 10px;
      background-color: var(--color3);
      border-radius: var(--box-radius);
      color: #fff;
    }
  }
  .press-cover{
    max-width:100%;
    max-height: 300px;
    object-fit:cover;
    margin:12px 0;
    border-radius: 6px;
  }
}


::v-deep .pc-vue-quick-calendar ul li.day.isSelected,
::v-deep .pc-vue-quick-calendar ul li.day.isMarked::after {
  background-color: var(--font-color-active) !important;
  background: var(--font-color-active) !important;
  color: white !important;
}
::v-deep .pc-vue-quick-calendar ul li:hover {
  background-color: var(--font-color-hover) !important;
}
::v-deep .pc-vue-quick-calendar ul li.day.isToday {
  color: var(--font-color-active);
}

/////////////////

@media (max-width: 528px) {
  .press-row {
    padding: 0px 0px 18px 0px;
  }
  
}

.pager {
  margin-top: 24px;
  overflow: auto;
  width: 100%;
}

@media (min-width: 768px) {
  .user-box,
  .components-box {
    margin: 24px;
  }
  .user-press-box{
    margin-top:12px;
  }
  .user-press {
    margin-top: 24px;
  }
}
@media (max-width: 710px) {
  .title{
    left: -8px;
  }
  .box-bg {
    border-radius: 0px;
  }
  .user-box {
    .user-head-box {
      .avtar {
        height: 64px;
        width: 64px;
      }
      .user-info {
        font-size: 14px;
        .desc {
          margin-top: 12px;
        }
      }
      .moblie-box {
        display: flex;
        align-content: center;
        justify-content: center;
        align-items: center;
        justify-content: center;
      }
      .computer-box {
        display: none;
      }
    }
  }
}
</style>